import os
from flask import Flask, jsonify,send_from_directory , request
from demo import read_csv_file, homeData_upload
from image_create import plot_hospital_visits, plot_monthly_visits
from testmodel import initModel
import pandas as pd  # 使用pandas来处理CSV数据
from flask_cors import CORS

UPLOAD_FOLDER_IMG = './images/'
dataSet_URL = './dataSet.csv'
UPLOAD_FOLDER_POSITIVES = './positives_test.csv'
UPLOAD_FOLDER = 'uploads/'

app = Flask(__name__)
CORS(app)
app.config['UPLOAD_FOLDER_IMG'] = UPLOAD_FOLDER_IMG
# 实现选择文件的功能
@app.route('/upload', methods=['POST'])
def upload_file():
    # 检查请求中是否包含文件
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400
    file = request.files[dataSet_URL]
    # 如果用户没有选择文件，浏览器也可能提交一个没有文件名的空部分
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400
    if file and file.filename.endswith('.csv'):
        # 保存文件到指定目录
        filename = file.filename
        filepath = os.path.join(UPLOAD_FOLDER, filename)
        file.save(filepath)
        return jsonify({"message": "File uploaded successfully", "filename": filename}), 200
    else:
        return jsonify({"error": "File must be a CSV"}), 400

# 读取csv文件
@app.route('/api/data_test', methods=['GET'])
def get_data_test():
    # 读取 CSV 文件并返回所有数据
    df = read_csv_file(UPLOAD_FOLDER_POSITIVES)
    # 返回 DataFrame 的 JSON 表示
    return jsonify(df)

# 首页数据上传
@app.route('/api/data', methods=['GET','POST'])
def getHomeData():
    df = pd.read_csv(dataSet_URL)
    data = homeData_upload(df)
    return jsonify(data)

# 模型训练的各种指标
@app.route('/api/score', methods=['GET'])
def get_score_from_model():
    # 假设 initModel() 返回一个元组，包含模型的评估指标
    acc_test, p_test, r_test, f1_test = initModel()  # 注意：这里假设 initModel() 已经在其他地方定义

    # 计算并格式化评估指标
    metrics = {
        "accuracy": round(acc_test * 100, 2),
        'precision': round(p_test * 100, 2),
        'recall': round(r_test * 100, 0),  # 如果您想要整数形式的召回率
        'f1_score': round(f1_test * 100, 2)
    }
    response_data = {
        'metrics': metrics
    }
    return jsonify(response_data)
# 返回绘制的各种图片
@app.route('/images/<filename>')
def uploaded_file(filename):
    # 检查文件名以防止路径遍历等安全问题
    if '..' in filename or filename.startswith('.'):
        return 'Bad Request', 400
    if not os.path.exists(os.path.join(UPLOAD_FOLDER_IMG, filename)):
        return 'File not found', 404
    return send_from_directory(UPLOAD_FOLDER_IMG, filename)

# 获取每个医院的病患数量折线图
@app.route('/api/plot/hospital_visits')
def get_hospital_visits_plot():
    # 生成并保存图表
    plot_hospital_visits(dataSet_URL)
    # 返回图片文件
    filename = 'hospital_visits.png'
    return send_from_directory(app.config['UPLOAD_FOLDER_IMG'], filename)
# 获取每个月数的病患数量饼图
@app.route('/api/plot/monthly_visits')
def get_monthly_visits_plot():
    # 生成并保存图表
    plot_monthly_visits(dataSet_URL)
    # 返回图片文件
    filename = 'monthly_visits.png'
    return send_from_directory(app.config['UPLOAD_FOLDER_IMG'], filename)

if __name__ == '__main__':
    app.run(debug=True, port=5000)